<template>
	<view class="account-assign-container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">账号分配</text>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 错误状态 -->
		<view v-else-if="error" class="error-container">
			<text class="error-text">{{ error }}</text>
			<u-button type="error" @click="reloadData">重试</u-button>
		</view>

		<!-- 主内容区域 -->
		<view v-else class="main-content">
			<!-- 搜索区域 -->
		<view class="search-section">
			<view class="search-bar">
				<u-input 
					type="text" 
					v-model="searchKeyword" 
					placeholder="搜索用户名"
					@confirm="handleSearch"
				/>
			</view>
			<u-button 
				type="primary" 
				size="medium"
				@click="handleSearch"
				:disabled="!searchKeyword.trim() || searching"
				:loading="searching"
			>
				搜索
			</u-button>
		</view>

			<!-- 用户列表区域 -->
			<view class="user-list-section">
				<view class="section-title">用户列表</view>
				<view v-if="searching" class="search-loading">
					<u-loading size="small"></u-loading>
					<text>搜索中...</text>
				</view>
				<view v-else-if="users.length === 0 && searchKeyword" class="empty-search">
					<text>未找到匹配的用户</text>
				</view>
				<view v-else-if="users.length === 0" class="empty-list">
					<text>暂无用户数据</text>
				</view>
				<view class="user-list">
					<view v-for="user in users" :key="user.id" class="user-item" @click="selectUser(user)">
						<view class="user-info">
							<text class="user-name">{{ user.username }}</text>
							<text class="user-role">{{ user.role?.message || '普通用户' }}</text>
						</view>
						<view class="user-status" :class="{'status-active': user.status?.code === 1}">
							{{ user.status?.message || '未知状态' }}
						</view>
					</view>
				</view>
			</view>

			<!-- 账号分配区域 -->
			<view class="assign-section">
				<view class="section-title">账号分配</view>
				<view v-if="selectedUser" class="selected-user-info">
					<text class="selected-text">已选择用户: {{ selectedUser.username }}</text>
				</view>
				<view v-else class="no-selection">
					<text>请先选择一个用户</text>
				</view>

				<!-- 账号选择列表 -->
				<view class="account-selection">
					<view v-if="availableAccounts.length === 0" class="empty-accounts">
						<text>暂无可用账号</text>
					</view>
					<!-- 性能优化：使用v-memo减少不必要的重渲染 -->
					<view v-for="account in availableAccounts" 
						:key="account.account_id" 
						v-memo="[assignedAccount?.account_id, account.status]"
						class="account-option" 
						:class="{ 'selected': assignedAccount?.account_id === account.account_id, 'disabled': account.status !== 1 }" 
						@click="account.status === 1 && selectAccount(account)">
						<view class="account-info">
							<text class="account-name">{{ account.username }}</text>
							<text class="account-balance">余额: ¥{{ account.balance || 0 }}</text>
							<text v-if="account.status !== 1" class="account-status-disabled">账号已禁用</text>
						</view>
						<u-icon v-if="assignedAccount?.account_id === account.account_id" name="checkbox-mark" size="20" color="#007AFF"></u-icon>
					</view>
				</view>

				<!-- 分配按钮 -->
				<u-button type="primary" @click="assignAccountfn" :disabled="!canAssign || assigning" :loading="assigning">
					{{ assigning ? '分配中...' : '确认分配' }}
				</u-button>
			</view>
		</view>
	</view>
	<u-top-tips ref="uTipsRef"></u-top-tips>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted} from 'vue';
import { SERVER_BASE_URL, searchAccount, searchUser, assignAccount } from '@/static/apis/wzry';
	
	// 响应式数据
	const loading = ref(false);
	const error = ref('');
	const searchKeyword = ref('');
	const searching = ref(false);
	const users = ref([]);
	const selectedUser = ref(null);
	const assignedAccount = ref(null);
	const availableAccounts = ref([]);
	const uTipsRef = ref();
	const assigning = ref(false); // 分配中状态
	
	// 计算属性
	const canAssign = computed(() => {
		return selectedUser.value && assignedAccount.value;
	});
	

	
	// 生命周期钩子
	onMounted(() => {
		loadInitialData();
	});
	
	
	
	// 加载初始数据
	async function loadInitialData() {
		try {
			loading.value = true;
			error.value = '';
			
			// 调用实际的API获取可用账号
			const accountsResponse = await searchAccount({status: "unassigned"});
			
			// 检查API响应
			if (accountsResponse.code === 0 && accountsResponse.data) {
				// 处理API返回的账号数据，确保使用正确的字段映射
				availableAccounts.value = accountsResponse.data.map(account => ({
					account_id: account.account_id, // 使用account_id作为唯一标识
					username: account.username,
					password: account.password, // 保留密码信息
					phone: account.phone,
					balance: parseFloat(account.balance) || 0, // 转换余额为数字类型
					create_by: account.create_by,
					current_owner: account.current_owner,
					status: account.current_owner === null ? 1 : 0, // 根据current_owner判断状态：1为可用，0为已分配
					create_time: account.create_time,
					update_time: account.update_time
				}));
			} else {
				// 处理API返回错误但不是异常的情况
				showTips(accountsResponse.message || '获取账号数据失败', 'error');
				availableAccounts.value = [];
			}
			
			loading.value = false;
		} catch (err) {
			error.value = handleApiError(err, '加载初始数据失败');
			console.error('加载数据错误:', err);
			loading.value = false;
		}
	}
	
	// 重新加载数据
	function reloadData() {
		loadInitialData();
	}
	
	// 处理用户搜索
	async function handleSearch() {
		const keyword = searchKeyword.value.trim();

		// 验证输入
		if (!keyword) {
			showTips('请输入搜索关键词', 'warning');
			return;
		}

		try {
			searching.value = true;
			users.value = []; // 清空当前结果，显示加载效果
			
			// 调用实际的搜索API
			const searchResponse = await searchUser({"keyword": keyword});
			
			// 检查API响应
			if (searchResponse.code === 0 && searchResponse.data) {
				// 处理API返回的用户数据，确保使用user_id作为唯一标识
				users.value = searchResponse.data.map(user => ({
					id: user.user_id, // 使用user_id作为唯一标识
					username: user.username,
					role: user.role,
					status: user.status,
					avatar: user.avatar,
					create_time: user.create_time,
					update_time: user.update_time
				}));
				
				// 根据搜索结果显示提示
				if (users.value.length === 0) {
					showTips('未找到相关用户，请尝试其他关键词', 'info');
				} else {
					showTips(`找到 ${users.value.length} 位用户`, 'success');
				}
			} else {
				// 处理API返回错误但不是异常的情况
				showTips(searchResponse.message || '搜索失败，请重试', 'error');
				users.value = [];
			}
			
		} catch (err) {
			console.error('搜索用户错误:', err);
			users.value = [];
			
			// 处理API错误
			handleApiError(err, '搜索用户失败');
		} finally {
			searching.value = false;
		}
	}
	


	
	// 选择用户
	function selectUser(user) {
		selectedUser.value = user;
		// 选择用户后可以清空已选账号，让用户重新选择
		assignedAccount.value = null;
	}
	
	// 选择账号
	function selectAccount(account) {
		assignedAccount.value = account;
	}
	
	// 分配账号
	async function assignAccountfn() {
		console.log(selectedUser.value);
		
		// 分配账号逻辑
		if (!canAssign.value) return;
		
		try {
			assigning.value = true;
			
			// 调用实际的分配API
			const assignResponse = await assignAccount({
				owner_id: selectedUser.value.id,
				account_id: assignedAccount.value.account_id
			});
			
			// 检查API响应
			if (assignResponse.code === 0) {
				// 分配成功
				showTips(assignResponse.message || '账号分配成功', 'success');
				
				// 更新可用账号列表
				const accountIndex = availableAccounts.value.findIndex(
					acc => acc.account_id === assignedAccount.value.account_id
				);
				
				if (accountIndex !== -1) {
					// 更新账号状态和所有者信息
					availableAccounts.value[accountIndex].status = 0; // 标记为已分配
					availableAccounts.value[accountIndex].current_owner = {
						user_id: selectedUser.value.id,
						username: selectedUser.value.username
					};
				}
				
				// 重置选择
				selectedUser.value = null;
				assignedAccount.value = null;
			} else {
				// 处理API返回错误但不是异常的情况
				showTips(assignResponse.message || '账号分配失败，请重试', 'error');
			}
			
		} catch (err) {
			console.error('账号分配失败:', err);
			
			// 处理API错误
			handleApiError(err, '账号分配失败');
		} finally {
			assigning.value = false;
		}
	}
	
	// 显示提示信息
	function showTips(message, type = 'info') {
		if (uTipsRef.value) {
			uTipsRef.value.show({
				title: message,
				type,
				duration: 2000
			});
		} else {
			// 如果u-tips组件不可用，使用原生提示
			uni.showToast({
				title: message,
				icon: type === 'success' ? 'success' : 'none',
				duration: 2000
			});
		}
	}
	

	


	
	// 处理API错误
	function handleApiError(error, defaultMessage = '操作失败，请重试') {
		let errorMessage = defaultMessage;
		
		// 解析常见的错误格式
		if (error.response) {
			// 服务器返回错误响应
			if (error.response.data && error.response.data.message) {
				errorMessage = error.response.data.message;
			} else if (error.response.status === 401) {
				errorMessage = '登录已过期，请重新登录';
			} else if (error.response.status === 403) {
				errorMessage = '没有权限执行此操作';
			} else if (error.response.status === 404) {
				errorMessage = '请求的资源不存在';
			} else if (error.response.status >= 500) {
				errorMessage = '服务器内部错误，请稍后重试';
			}
		} else if (error.request) {
			// 请求已发出但没有收到响应
			errorMessage = '网络连接异常，请检查网络';
		} else if (error.message) {
			// 请求设置时发生错误
			errorMessage = error.message;
		}
		
		console.error('API错误:', error);
		showTips(errorMessage, 'error');
		return errorMessage;
	}
</script>

<style scoped lang="scss">
	/* 主容器样式 */
	.account-assign-container {
		padding: 16px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 搜索栏样式 */
	.search-section {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	/* 页面标题样式 */
	.page-header {
		margin-bottom: 20px;
		padding-bottom: 12px;
		border-bottom: 2px solid #e0e0e0;
	}

	.page-title {
		font-size: 20px;
		font-weight: bold;
		color: #333;
	}

	/* 加载状态样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 0;
	}

	.loading-spinner {
		width: 40px;
		height: 40px;
		border: 3px solid #f3f3f3;
		border-top: 3px solid #3498db;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 12px;
	}

	.loading-text {
		color: #666;
		font-size: 14px;
	}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	/* 错误状态样式 */
	.error-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 0;
		text-align: center;
	}

	.error-text {
		color: #e74c3c;
		font-size: 14px;
		margin-bottom: 16px;
	}

	/* 主内容区域 */
	.main-content {
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	/* 搜索区域样式 */
	.search-section {
		background-color: white;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	/* 用户列表区域样式 */
	.user-list-section {
		background-color: white;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.section-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 16px;
	}

	.search-loading, .empty-search, .empty-list {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30px 0;
		color: #999;
		font-size: 14px;
		gap: 8px;
	}

	.user-list {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.user-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px;
		background-color: #f8f8f8;
		border-radius: 6px;
		transition: background-color 0.3s ease;
	}

	.user-item:active {
		background-color: #e8e8e8;
	}

	.user-info {
		flex: 1;
	}

	.user-name {
		font-size: 15px;
		font-weight: bold;
		color: #333;
		margin-bottom: 4px;
	}

	.user-role {
		font-size: 13px;
		color: #666;
	}

	.user-status {
		padding: 4px 12px;
		border-radius: 12px;
		font-size: 12px;
		color: #999;
		background-color: #e0e0e0;
	}

	.user-status.status-active {
		background-color: #d4edda;
		color: #155724;
	}

	/* 分配区域样式 */
	.assign-section {
		background-color: white;
		border-radius: 8px;
		padding: 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.selected-user-info, .no-selection {
		padding: 12px;
		background-color: #f8f8f8;
		border-radius: 6px;
		margin-bottom: 16px;
		font-size: 14px;
	}

	.selected-text {
		color: #333;
	}

	.no-selection {
		color: #999;
	}

	/* 账号选择列表样式 */
	.account-selection {
		display: flex;
		flex-direction: column;
		gap: 12px;
		margin-bottom: 20px;
	}

	.account-option {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px;
		background-color: #f8f8f8;
		border-radius: 6px;
		transition: all 0.3s ease;
		border: 2px solid transparent;
	}

	.account-option.selected {
		background-color: #e3f2fd;
		border-color: #2196f3;
	}

	.account-option:active {
		background-color: #e0e0e0;
	}

	.account-info {
		flex: 1;
	}

	.account-name {
		font-size: 15px;
		font-weight: bold;
		color: #333;
		margin-bottom: 4px;
	}

	.account-balance {
		font-size: 13px;
		color: #e74c3c;
		margin-bottom: 4px;
	}
	
	.account-status-disabled {
		font-size: 12px;
		color: #e74c3c;
	}
	
	.account-option.disabled {
		opacity: 0.5;
		pointer-events: none;
	}
	
	.empty-accounts {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40px 0;
		color: #999;
		font-size: 14px;
	}
</style>
